﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Api1.Util
{
    /// <summary>
    /// 网络访问类
    /// </summary>
    class HttpClient
    {
        public static Boolean debug =Convert.ToBoolean(OperateIniFile.ReadIniData("DB", "debug", "false"));
        /// <summary>  
        /// 指定Post地址使用Get 方式获取全部字符串  
        /// </summary>  
        /// <param name="url">请求后台地址</param>  
        /// <param name="content">ie=utf-8&source=txt&query=hello</param>  
        /// <returns></returns>  
        public static String Post(string url, string content)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Timeout = 3000;
            #region 添加Post 参数  
            byte[] data = Encoding.UTF8.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion            
            try {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.GatewayTimeout||resp.StatusCode == HttpStatusCode.BadGateway) {
                    LogHelper.WriteLog(typeof(HttpClient), "链接超时或服务器异常");
                    return "";
                }
                Stream stream = null;
                try
                {
                     stream = resp.GetResponseStream();
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                        if (debug)
                        {
                            LogHelper.WriteLog(typeof(HttpClient), result);
                        }
                    }
                }finally{
                    if (stream != null) {
                        stream.Close();
                    }
                }
                
                if (resp.ContentType.Contains("text/xml"))
                {
                    //获取响应内容                 
                    result = result.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "").Replace("<string xmlns=\"http://tempuri.org/\" />", "").Replace("<string xmlns=\"http://tempuri.org/\">", "").Replace("<int xmlns=\"http://tempuri.org/\">", "").Replace("</string>", "").Replace("</int>", "").Replace("\r", "").Replace("\n", ""); ;
                   // Console.WriteLine(result);
                    if (String.IsNullOrWhiteSpace(result))
                    {
                        return null;
                    }
                }
            } catch (Exception e) {
                ApiServiceImpl.WriteLog(typeof(HttpClient), e);
                return null;
            }
            return result;
        }

        public static String Get(String strURL) {           
            System.Net.HttpWebRequest request;
            // 创建一个HTTP请求  
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 3000;
            System.Net.HttpWebResponse response;
            string responseText = "";
            try {
                response = (System.Net.HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.GatewayTimeout || response.StatusCode == HttpStatusCode.BadGateway)
                {
                    LogHelper.WriteLog(typeof(HttpClient), "链接超时或服务器异常");
                    return "";
                }
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseText = myreader.ReadToEnd();
                myreader.Close();
                if (debug)
                {
                    LogHelper.WriteLog(typeof(HttpClient), responseText);
                }                
                if (response.ContentType.Contains("text/xml"))
                {
                    //获取响应内容                 
                    responseText = responseText.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "").Replace("<string xmlns=\"http://tempuri.org/\" />", "").Replace("<string xmlns=\"http://tempuri.org/\">", "").Replace("<int xmlns=\"http://tempuri.org/\">", "").Replace("</string>", "").Replace("</int>", "").Replace("\r", "").Replace("\n", ""); ;
                    if (String.IsNullOrWhiteSpace(responseText))
                    {
                        return null;
                    }
                }
            } catch (Exception e) {
                ApiServiceImpl.WriteLog(typeof(HttpClient), e);
                return null;
            }

            // List<Dictionary<String, Object>> list = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(responseText);           
            return responseText;         
        }
        /// <summary>
        /// 获取原生/没有经过处理的的数据
        /// </summary>
        /// <param name="strURL"></param>
        /// <returns></returns>
        public static String GetNative(String strURL)
        {
            System.Net.HttpWebRequest request;
            // 创建一个HTTP请求  
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.ContentType = "text/xml";
            request.Timeout = 3000;
            System.Net.HttpWebResponse response;
            string responseText = "";
            try
            {
                response = (System.Net.HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.GatewayTimeout || response.StatusCode == HttpStatusCode.BadGateway)
                {
                    LogHelper.WriteLog(typeof(HttpClient), "链接超时或服务器异常");
                    return "";
                }
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseText = myreader.ReadToEnd();
                myreader.Close();
                if (debug)
                {
                    LogHelper.WriteLog(typeof(HttpClient), responseText);
                }
            }
            catch (Exception e)
            {
                ApiServiceImpl.WriteLog(typeof(HttpClient), e);
                return null;
            }
            return responseText;
        }
        /// <summary>
        /// 成功时候返回的模板
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public static Dictionary<String, Object> Success(String Msg = "",Object Data=null) {
            return new Dictionary<string, object> (){ {"Flag",true },{ "Msg",Msg},{"Data",Data }};
        }
        /// <summary>
        /// 失败时候返回的模板
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public static Dictionary<String, Object> Error(String Msg = "",Object Data = null)
        {
            return new Dictionary<string, object>() { { "Flag", false }, { "Msg", Msg }, { "Data", Data } };
        }

        /// <summary>  
        /// 测试post   返回结果不做任何转换
        /// </summary>  
        /// <param name="url">请求后台地址</param>  
        /// <param name="content">ie=utf-8&source=txt&query=hello</param>  
        /// <returns></returns>  
        public static String TestPost(string url, string content)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.Timeout = 3000;
            req.ContentType = "application/x-www-form-urlencoded";
            Console.WriteLine(url);
            Console.WriteLine(content);
            #region 添加Post 参数  
            byte[] data = Encoding.UTF8.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion            
            try
            {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                if (resp.StatusCode == HttpStatusCode.GatewayTimeout || resp.StatusCode == HttpStatusCode.BadGateway)
                {
                    LogHelper.WriteLog(typeof(HttpClient), "链接超时或服务器异常");
                    return "";
                }
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    if (debug)
                    {
                        LogHelper.WriteLog(typeof(HttpClient), result);
                    }
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                ApiServiceImpl.WriteLog(typeof(HttpClient), e);
                return e.Message.ToString();
            }           
            return result;
        }
    }
}
